package com.zhkj.lib.widget

import android.content.Context
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.TextView
import com.zhkj.lib.R
import razerdp.basepopup.BasePopupWindow

class LoadingStatuesDialog(context: Context) : BasePopupWindow(context) {

    private var imageView: ImageView? = null
    private var textView: TextView? = null
    private val rotate: RotateAnimation = RotateAnimation(
        0F,
        359F,
        Animation.RELATIVE_TO_SELF,
        0.5F,
        Animation.RELATIVE_TO_SELF,
        0.5F
    ).apply {
        interpolator = LinearInterpolator()
        duration = 1500
        repeatCount = -1
        fillAfter = false
    }

    init {
        isOutSideTouchable = false
        setOutSideDismiss(false)
        setBackPressEnable(false)
        setAdjustInputMethod(false)
    }

    override fun onCreateContentView(): View {
        return createPopupById(R.layout.dialog_progress)
    }

    override fun onViewCreated(contentView: View?) {
        contentView?.let {
            imageView = it.findViewById(R.id.ivStatus)
            textView = it.findViewById(R.id.tvStatus)
        }
    }

    private fun startRotate() {
        imageView?.let {
            it.animation = rotate
            it.startAnimation(rotate)
        }
    }

    private fun stopRotate() {
        imageView?.clearAnimation()
    }

    override fun onDismiss() {
        if (imageView?.animation != null) imageView?.clearAnimation()
        super.onDismiss()
    }

    fun showLoading(content: String? = null) {
        imageView?.setImageResource(R.drawable.dialog_loading)
        textView?.text = content ?: context.resources.getString(R.string.loading)
        startRotate()
        showPopupWindow()
    }

    fun showSuccess(content: String) {
        stopRotate()
        textView?.text = content
        imageView?.setImageResource(R.drawable.dialog_success)
        showPopupWindow()
    }

    fun showError(content: String) {
        stopRotate()
        textView?.text = content
        imageView?.setImageResource(R.drawable.dialog_error)
        showPopupWindow()
    }
}